import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:audio_data/audio_data.dart';
import 'package:mybase/base/tool/pprint/FFLog.dart';
import 'package:mybase/base/widget/layout/FFLineContainer.dart';
import 'package:mybase/base/widget/layout/FFTextButton.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with AudioDataStream {
  final _audioDataPlugin = AudioData();

  @override
  void initState() {
    super.initState();

    _audioDataPlugin.add(this);
    AudioData.init();
  }

  @override
  void dispose() {
    _audioDataPlugin.remove(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: FFLineContainer(
          direction: Axis.vertical,
          children: [
            FFTextButton(
              text: "开启",
              fontSize: 16,
              fontColor: Colors.red,
              padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 20),
              onClick: () async {

                PermissionStatus status = await Permission.microphone.request();

                if (status != PermissionStatus.granted) {
                  FFLog.error("没有录音权限");
                  return;
                }

                _audioDataPlugin.startRecord();
              },
            ),
            FFTextButton(
              text: "关闭",
              fontSize: 16,
              fontColor: Colors.red,
              padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 20),
              onClick: () {
                _audioDataPlugin.stopRecord();
              },
            ),
          ],
        ),
      ),
    );
  }

  @override
  onStream(Uint8List? list) {
    if (list == null) return;
    print("长度 ${list.length} 前20条为 ${list.sublist(0,20)}");

  }
}
